package com.crealth.crmserver;

import java.nio.ByteOrder;

import org.apache.log4j.Logger;
import org.apache.mina.core.buffer.BufferDataException;
import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.AttributeKey;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolDecoderAdapter;
import org.apache.mina.filter.codec.ProtocolDecoderOutput;

import com.crealth.msg.NetMessageData;

public final class GateWayDecoder extends ProtocolDecoderAdapter {
	private static Logger errorLog = Logger.getLogger("error_log");
	
	
	private final AttributeKey BUFFER = new AttributeKey(getClass(), "remains");
	//private static final int MAX_BUFFER_LENGTH = 1024 * 512;
	private static final int MAX_LEN = 5*1024*1024;
	
	
	@Override
	public void decode(IoSession session, IoBuffer in, ProtocolDecoderOutput out) throws Exception {
		in.order(ByteOrder.BIG_ENDIAN);
		byte[] buf = (byte[])session.getAttribute(BUFFER);
		if (null != buf) {
			IoBuffer newBuf = IoBuffer.allocate(buf.length + in.remaining());
			newBuf.put(buf);
			newBuf.put(in);
			newBuf.flip();
			
			in = newBuf;
			session.removeAttribute(BUFFER);
		}

		while (true){
			try {
				if (!in.prefixedDataAvailable(4, MAX_LEN)) {   //每次最大读取4KB的内容
					buf = new byte[in.remaining()];
					in.get(buf);
					session.setAttribute(BUFFER, buf);
					return;
				}
			} catch (BufferDataException e) {
				errorLog.error("协议超过最大读取值");
			}
			
			NetMessageData req = parseMessage(in, session);
			if (null != req) {
				out.write(req);
			}
		}
	}
	
	private NetMessageData parseMessage(IoBuffer in, IoSession session) throws Exception {
		NetMessageData reqMsg = null;
		if (in.remaining() > 4) {
			int bodyLen = in.getInt();
			if (bodyLen > 0 && in.remaining() >= bodyLen) {		
				byte[] msgBody = new byte[bodyLen];
				in.get(msgBody);
				reqMsg = new NetMessageData(bodyLen, msgBody);
			}
		}
		
		return reqMsg;
	}
}
